﻿using LowCoding.Application.Sys.User;
using LowCoding.Common;
using LowCoding.Common.JWT;
using LowCoding.Common.Security;
using LowCoding.Domain;
using LowCoding.Dto.Sys;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;

namespace LowCoding.API.Controllers.sys.User
{
    /// <summary>
    /// 用户Api
    /// </summary>
    /// [Authorize]
    [Route("api/[controller]/[action]")]
    [ApiController]
    public class SysUserController : BaseController
    {
        /// <summary>
        /// 依赖注入
        /// </summary>
        private readonly ISysUserService _sysUserService;
        private readonly JWTTokenOptions _tokenOptions;
        public readonly IBaseDatatable _datatable;
        public SysUserController(ISysUserService sysUserService, JWTTokenOptions tokenOptions, IBaseDatatable datatable)
        {
            _sysUserService = sysUserService;
            _tokenOptions = tokenOptions;
            _datatable = datatable;
        }

        [HttpGet]
        public void daatable() 
        {
             _datatable.DataBase();
        }

        /// <summary>
        /// 用户登录(接口可用)
        /// </summary>
        /// <param name="loginModel"></param>
        /// <returns></returns>
        [HttpPost("CheckLoginInfo")]
        [AllowAnonymous]
        public async Task<ResponseMessageModel> CheckLoginInfo([FromForm] LoginInput loginModel)
        {
            //IsNullOrWhiteSpace:指定的字符串是 null、空还是仅由空白字符组成。
            //这里是指定传过来的参数登录代码是否是null 还是仅由空字符组
            if (string.IsNullOrWhiteSpace(loginModel.CmpCode))
            {
                return Fail("登录代码不能为空");
            }
            //指定传过来的参数用户账号是否是null 还是仅由空字符组
            if (string.IsNullOrWhiteSpace(loginModel.Code))
            {
                return Fail("用户账号不能为空");
            }
            //指定传过来的参数密码是否是null 还是仅由空字符组
            if (string.IsNullOrWhiteSpace(loginModel.Password))
            {
                return Fail("用户密码不能为空");
            }
            //通过判断 传过来的参数密码 进行加密默认密码的赋值
            loginModel.Password = MD5Encrypt.GetMD5(loginModel.Password);
            //调用检验账号密码的方法进行验证 如果等于空的话 就显示密码账户错误
            var userDto = await _sysUserService.CheckUserLoginWithMd5Pwd(loginModel);
            if (userDto == null)
            {
                return Fail("用户名或者密码错误");
            }
            //如果状态是无效的 那么提示该账号不可用
            //GetEnumValue 获取枚举类型 这里用枚举也可以防止 修改状态 也可以优化系统性能
            if (userDto.UsrStatus != Isvalid.Yes.GetEnumValue())
            {
                return Fail("当前账号不可用");
            }
            //实例化Dto
            var playloadDto = new LoginUserDto()
            {
                UserId = userDto.UserId,
                UsrFltId = userDto.UsrFltId,
                UsrName = userDto.UsrName,
                IsRoleAdmin = true,
                UserCode = userDto.UsrCode,
                PlatForm = "1"
            };
            //根据用户Id获取Token
            string Token = AppManager.GetJwtString(playloadDto, DateTime.Now.AddHours(2));
            //string refreshToken = AppManager.GetJwtString(playloadDto, DateTime.Now.AddDays(1));
            var token = new JwtTokenHelper().AuthorizeToken(playloadDto, _tokenOptions);
            //return Success(new
            //{
            //    User = playloadDto,
            //    Token = token,
            //    RefreshToken = token
            //    //RefreshToken = "Bearer " + refreshToken
            //    //token = token
            //});
            return Success(new // vue Admin 格式规范
            {
                User = playloadDto,
                Token = token.Access_token,
                RefreshToken = token.Access_token
            });
        }

        /// <summary>
        /// 用户注册(接口可用)
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpPost, Route("insert")]
        [AllowAnonymous]
        public async Task<ResponseMessageModel> SysUserInsert([FromQuery] SysUserInput input)
        {
            return Success(await _sysUserService.UserInsert(input));
        }

        /// <summary>
        /// 用户列表显示(接口可用)
        /// </summary>
        /// <returns></returns>
        [HttpGet, Route("Getlist")]
        [Authorize]
        public async Task<ResponseMessageModel> Getlist()
        {
            return await _sysUserService.Getlist();

        }

        /// <summary>
        /// 删除用户信息(接口可用)
        /// </summary>
        /// <param name="id">用户ID</param>
        /// <returns></returns>
        [HttpDelete]
        [Authorize]
        public async Task<ResponseMessageModel> DeleteUserById(string id)
        {
            return await _sysUserService.DeleteUserById(id);
        }

        /// <summary>
        /// 修改用户信息(接口可用)
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpPut, Route("Update")]
        [Authorize]
        public async Task<ResponseMessageModel> UpdateUserAsync(SysUserInputUpt_Dto input)
        {
            return Success(await _sysUserService.UpdateUserAsync(input));
        }

        /// <summary>
        /// 查询单条用户（接口可用）
        /// </summary>
        /// <param name="key"></param>
        /// <returns></returns>
        [HttpGet("DisplayKey")]
        [AllowAnonymous]
        public async Task<ResponseMessageModel> SysUserQuery([FromQuery] string key)
        {
            return Success(await _sysUserService.GetSingleAsync(key));
        }

        /// <summary>
        /// 分页查询用户列表（接口可用）
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpGet("Display")]
        [AllowAnonymous]
        public async Task<ResponseMessageModel> SysUserPage([FromQuery] SysUserSearchInput input)
        {
            return Success(await _sysUserService.GetPageListAsync(input));
        }

         
        /// <summary>
        /// 批量删除用户（接口可用）
        /// </summary>
        /// <param name="keys"></param>
        /// <returns></returns>
        [HttpDelete("DeleteKeys")]






        [AllowAnonymous]
        public async Task<ResponseMessageModel> DelUserAsync([FromForm] List<string> keys)
        {
            return Success(await _sysUserService.DelUserAsync(keys));
        }

        [HttpGet]
        public ResponseMessageModel getsysName()
        {
            return Success(_sysUserService.sysNames());
        }
    }
}
